package com.qf.first.controller;

import com.qf.first.base.exception.ControllerException;
import com.qf.first.base.pojo.vo.UserVo;
import com.qf.first.base.result.RespVo;
import com.qf.first.base.result.ResultCode;
import com.qf.first.base.untils.ShiroUtils;
import com.qf.first.pojo.request.UserRequest;
import com.qf.first.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.Serializable;


@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Resource
    UserService userService;
    @PostMapping("/login")
    public RespVo login(@NotNull(message = "用户名不能为空") String username, @NotNull(message = "密码不能为空") String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            SecurityUtils.getSubject().login(token);
        } catch (IncorrectCredentialsException e) {
            throw new ControllerException(ResultCode.ACCOUNT_LOGIN_ERROR);
        } catch (ExcessiveAttemptsException e) {
            throw new ControllerException(ResultCode.LOGIN_ERROR_OFEN);
        }catch (AccountException e){
            throw new ControllerException(ResultCode.ACCOUNT_LOGIN_ERROR);
        }
        Serializable id = ShiroUtils.getSession().getId();
        System.out.println(id);
        return RespVo.success(id);
    }

    @PostMapping("/register")
    public RespVo register(UserRequest user){
        String name =  user.getUsername();
        String password = user.getPassword();
        name = HtmlUtils.htmlEscape(name);
        user.setUsername(name);
        UserVo userVo = userService.checkUsername(name);
        if(userVo!=null){
            throw new ControllerException(ResultCode.USER_EXIT);
        }
      /*  String salt =new SecureRandomNumberGenerator().nextBytes().toString();
        int times= 2;
        String algorithmName="md5";
        String encodedPassword=new SimpleHash(algorithmName,password,salt,times).toString();
        user.setSalt(salt);*/
        String encryptedPassword = ShiroUtils.sha256(password);
        user.setPassword(encryptedPassword);
        int i = userService.addUser(user);
        if (i==0){
            throw new ControllerException(ResultCode.ERROR);
        }
        return RespVo.success("登录成功");
    }

}
